 #!/usr/bin/python

import os
import sys

import gtk
import cairo 

# Needs review
class Importer(object):
	def __init__(self):
		home = os.path.expanduser('~')
		importDirs = [
			"/usr/share/usp2/plugins",
			home + "/.usp2/plugins"]
		plugins = []
		for importDir in importDirs:
			if os.path.exists(importDir):
				sys.path.append(importDir)
				plugins += self._searchForPlugins(importDir)

		self.loaded = []
		for plugin in plugins:
			self.loaded.append(__import__(plugin))
	
	def plugins(self):
		return self.loaded
		
	def _searchForPlugins(self, path):
		candidates = []
		files = os.listdir(path)
		for file in files:
			full = path + "/" + file
			if os.path.isfile(full) and file.endswith('.py'):
				candidates.append(file[:-3])
		return candidates

# Temporary moved here
class TransparencyUtils(object):
	@staticmethod
	def clearWithColorExposeFunction(widget, event, color):
		context = widget.window.cairo_create()
		r, g, b, a = color
		context.set_source_rgba(r, g, b, a)
		context.set_operator(cairo.OPERATOR_SOURCE)
		context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height)
		context.clip()
		context.paint()
	
	@staticmethod
	def setColormapToScreenColormap(widget, screen = gtk.gdk.screen_get_default()):
		colormap = screen.get_rgba_colormap()
		if colormap == None:
			colormap = screen.get_rgb_colormap()
		widget.set_colormap(colormap)
		widget.set_app_paintable(True)
	
	@staticmethod
	def opacifyWidget(widget, alpha):
		TransparencyUtils.setColormapToScreenColormap(widget)
		widget.realize()
		style = widget.get_style()
		color = style.bg[gtk.STATE_NORMAL]
		bgColor = (color.red / 65536.0, color.green / 65536.0, color.blue / 65536.0, alpha)
		widget.connect('expose-event', TransparencyUtils.clearWithColorExposeFunction, bgColor)

# Find a better solution for configuration and remove the need for a singleton
class Singleton:
	# Shared state type of a singleton
	__sharedState = {}
	
	def __init__(self):
		self.__dict__ = self.__sharedState

# Temporary - replace with gnome counterpart
import xdg.Menu
from xdg.DesktopEntry import *

class XdgMenu:
	def __init__(self, menu):
		self.menu = xdg.Menu.parse(menu)
		self.categories = []
		self.categoryForName = {}
		self.entryNamesForCategoryName = {}
		
	def allCategories(self):
		if self.categories == []:
			self.categories = self.categoriesForMenu(self.menu)
			for category in self.categories:
				self.categoryForName[category.getName()] = category
		return self.categories
	
	def allEntries(self):
		entries = self.entriesFor(self.menu)
		entries.sort(lambda x,y: cmp(x.DesktopEntry.getName(), y.DesktopEntry.getName()))
		return entries
	
	def getCategoryFor(self, categoryName):
		for i in self.categories:
			if i.getName() == categoryName:
				return i
			
	def isEntryIn(self, entryName, categoryName):
		entryNames = self.entryNamesForCategoryName[categoryName]
		return entryName in entryNames

	def entriesFor(self, category):
		entries = []
		self.entryNamesForCategoryName[category.getName()] = []
		for entry in category.getEntries():
			if isinstance(entry, xdg.Menu.Menu):
				entries = entries + self.entriesFor(entry)
			elif isinstance(entry, xdg.Menu.MenuEntry):
				entries.append(entry)
				self.entryNamesForCategoryName[category.getName()].append(entry.DesktopEntry.getName())
				
		return entries
	
	def categoriesForMenu(self, menu):
		categories = []
		for entry in menu.getEntries():
			if isinstance(entry, xdg.Menu.Menu):
				categories.append(entry)
				categories = categories + self.categoriesForMenu(entry)
		return categories

# Helper method that needs a new home...
def setNameToTabs(noteBook, tabName):
	for index in range(noteBook.get_n_pages()):
			noteBook.set_tab_label_text(noteBook.get_nth_page(index), tabName[index])

# Helper method that needs a new home...
def clearWidgetChildren(widget):
	if len(widget.get_children()) > 0:
		for each in widget.get_children():
			each.destroy()

# Helper method that needs a new home...
def textMatchesCriterions(searchText, criterions):
		if not searchText:
			return True
		for criterion in criterions:
			#if re.search(searchText.lower(), criterion.lower()):
			if criterion.lower().find(searchText.lower()) != -1:
				return True
		return False

# Helper method that needs a new home...
def createCompareFuction(alwaysGreatest = None):
	return lambda x,y: x == alwaysGreatest and -1 or y == alwaysGreatest and 1 or cmp(x,y)

# Helper method that needs a new home...
def removeArgs(stringToExecute): 
	specials = ["%f","%F","%u","%U","%d","%D","%n","%N","%i","%c","%k","%v","%m","%M", "-caption","--view", "\"%c\""]
	return [element for element in stringToExecute if element not in specials]

# Helper method that needs a new home...
def execute(command, runInTerminal=False, useXdgOpen=False):
	command = removeArgs(command)
	os.chdir(os.path.expanduser("~"))
	if runInTerminal == True:
		command.insert(0, '-x')
		command.insert(0, 'gnome-terminal')
		pid = os.spawnvp(os.P_NOWAIT, '/usr/bin/gnome-terminal', command)
	else:
		if useXdgOpen == True:
			command.insert(0, 'xdg-open')
		pid = os.fork()
		if pid:
			os.spawnvp(os.P_NOWAIT,command[0], command)
			os._exit(0)

